# coding=utf-8
from PIL import Image
from pprint import pformat
import os

def rotatePattern(pattern, anchor):
    ax, ay = anchor
    w = len(pattern[0])
    h = len(pattern)
    return ([
            "".join(pattern[h-x-1][y] for x in range(h))
            for y in range(w)
            ], (h-1-ay,ax))


def generateImage(pattern, imageName, blockName="blue.png"):
    """ pattern: 
    ["###",
     "#**" ]
    imageName - output filename
    block - image for single block."""
    block = Image.open(blockName)
    bSize = block.size[0]
    w = len(pattern[0])
    h = len(pattern)
    resultImage = Image.new("RGBA", (bSize*w, bSize*h), (0,0,0,0))
    for x in range(w):
        for y in range(h):
            if pattern[y][x] == "#":
                resultImage.paste(block, (x*bSize, y*bSize))
    resultImage.save(imageName, "PNG")

blocks = [
        { 
            'name': "I",
            'pattern': [
                "#",
                "#",
                "#",
                "#",
                ],
            'anchor': (0,1),
            'colors': ['blue'],
            'priority':5

        },
        { 
            'name': "T",
            'pattern': [
                "###",
                "*#*",
                ],
            'anchor': (1,0),
            'colors': ['red'],
            'priority':5

        },
        { 
            'name': "S",
            'pattern': [
                "*##",
                "##*",
                ],
            'anchor': (1,1),
            'colors': ['green'],
            'priority':5

        },
        { 
            'name': "Z",
            'pattern': [
                "##*",
                "*##",
                ],
            'anchor': (1,1),
            'colors': ['brown'],
            'priority':5

        },
        { 
            'name': "O",
            'pattern': [
                "##",
                "##",
                ],
            'anchor': (0,0),
            'colors': ['purple'],
            'priority':5
        },
        { 
            'name': "J",
            'pattern': [
                "##",
                ],
            'anchor': (0,0),
            'colors': ['pink'],
            'priority':1
        },
        { 
            'name': "A",
            'pattern': [
                "#",
                ],
            'anchor': (0,0),
            'colors': ['black'],
            'priority':0
        },

        ]

white =[ 
        { 
            'name': "W",
            'pattern': ".",
            'anchor': (0,0),
            'imageName':'white.png',
            'groups' : ["W"],
            'mapping':{},
            'priority':0
        },
    ]
def generateAll():
    res = list(white)
    for b in blocks:
        for i in range(4):
            for color in b["colors"]:
                currentDir = os.path.dirname(os.path.realpath(__file__))
                imagesDir = os.path.join(currentDir, "images")
                try:
                    os.mkdir(imagesDir)
                except OSError:
                    pass
                name = "{1}-{0}{2}.png".format(b['name'], color, i)
                imagePath = os.path.join(imagesDir, name)
                blockImage = os.path.join(currentDir, color+".png")
                generateImage(b['pattern'], imagePath, blockImage)
                block = dict(b)
                del block["name"]
                del block["colors"]
                block["imageName"] = os.path.join("images", name)
                block["pattern"] = "\n".join(block["pattern"])
                block["groups"] = [b["name"][0]]
                block["mapping"] = {}
                res.append(block)
            b["pattern"], b["anchor"] = rotatePattern(b["pattern"], b["anchor"])
    with open(os.path.join(currentDir,"tiles.py"), "w") as f:
        f.write("# coding=utf-8\ntiles = {0}\n".format(pformat(res)).encode("utf-8"))

def main():
    generateAll()

if __name__ == "__main__":
    main()
